package com.husd.leetcode.string;

/**
 * @author hushengdong@gome.com.cn
 * @date 2022/6/14 16:36
 */
public class ValidIPV4 {

    public  void testIpV4() {

//        Assert.assertTrue(isValidIpv4("127.0.0.1"));
//        Assert.assertTrue(isValidIpv4("255.255.255.255"));
//        Assert.assertTrue(isValidIpv4("0.0.0.0"));
//        Assert.assertTrue(isValidIpv4("1.0.0.0"));
//        Assert.assertFalse(isValidIpv4("1"));
//        Assert.assertFalse(isValidIpv4("1."));
//        Assert.assertFalse(isValidIpv4(".127.0.0.1"));
//        Assert.assertFalse(isValidIpv4("127.0.0.1."));
//        Assert.assertFalse(isValidIpv4("127.0.0.256"));
//        Assert.assertFalse(isValidIpv4("256.0.0.1"));
//        Assert.assertFalse(isValidIpv4("127.256.0.1"));
//        Assert.assertFalse(isValidIpv4("127.0.256.1"));
//        Assert.assertFalse(isValidIpv4("127.0.0.256"));
//        Assert.assertFalse(isValidIpv4("-127.0.0.1"));
//        Assert.assertFalse(isValidIpv4("127.abc.0.1"));
//        Assert.assertFalse(isValidIpv4("127.#.0.1"));
//        Assert.assertFalse(isValidIpv4("127..0.0.1"));
//        Assert.assertFalse(isValidIpv4("127.00.0.1"));
//        Assert.assertFalse(isValidIpv4("127.01.0.1"));
    }

    private boolean isValidIpv4(String s) {

        if (s == null || s.length() == 0) return false;
        if (s.length() < 7 || s.length() > 15) return false;

        int pointCount = 0;
        int i = 0;
        char[] buf = new char[3]; //存储数字
        while (i < s.length()) {

            int j = 0;
            // 初始化
            for (int c = 0; c < 3; c++) {
                buf[c] = '~';
            }

            while (i < s.length() && s.charAt(i) != '.') {

                if(j >= 3) return false;

                buf[j] = s.charAt(i);
                i++;
                j++;
            }
            if(!isValidNum(buf)) {
                return false;
            }
            //遇到了. 计算下点的数量
            if(i < s.length() && s.charAt(i) == '.') {
                pointCount++;
            }
            //只能有3个点
            if(pointCount > 3) {
                return false;
            }

            i++;
        }
        return true;
    }

    private boolean isValidNum(char [] buf) {

        //没有数字
        if(buf[0] == '~') return false;

        // 以0开头只能是 0～～
        if(buf[0] == '0' && buf[1] == '~') return true;

        //不能以0开头
        if(!isValidNumBigThen0(buf[0]))  return false;

        int num = 0;
        int i = 0;
        while(i < 3 && buf[i] != '~') {

            //不是数字
            if (!isValidNum(buf[i])) return false;
            num = (int)(buf[i] - '0') + num * 10;
            i++;
        }
        return num >= 0 && num <= 255;
    }

    private  boolean isValidNum(char c) {

        return c >= '0' && c <= '9';
    }

    private  boolean isValidNumBigThen0(char c) {

        return c >= '1' && c <= '9';
    }
}
